import axios from "axios"
import {showLoading,hideLoading} from "@/utils/loading"
import {getToken} from "./auth"
import {Toast} from "vant"
// create an axios instance
const service = axios.create({
	baseURL: process.env.VUE_APP_SERVER_URL, // api的base_url
	timeout: 15000, // 请求超时时间
	useMock: false
})

// request拦截器
service.interceptors.request.use(
	config => {
		// Do something before request is sent
		//配置header
		let headers = getToken();
		for (var x in headers) {
			config.headers[x] = headers[x];
		}
		if(config.options && config.options.progress){
			config.onUploadProgress = (progressEvent)=>{
				config.options.progress(progressEvent);
			}
		}
		//显示全屏loading界面
		if (config.options && config.options.loading) {
			showLoading();
		}
		return config
	},
	error => {
		// Do something with request error
		//关闭loading
		hideLoading();
		Promise.reject(error)
	}
)

// respone拦截器
service.interceptors.response.use(
	/**
	 * 下面的注释为通过response自定义code来标示请求状态
	 * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
	 */
	response => {
		//关闭loading
		hideLoading();
		const res = response.data;
		if (res.flag == '0') {
			//flag为0标识返回正确结果,具体以实际业务为准,并在then中返回
			return Promise.resolve(res);
		}else{
			//一些其他状态码比如需要登录等,可统一在这里处理,并在catch中返回
			return Promise.reject(res);
		}
	},
	error => {
		if (error && error.response) {
			switch (error.response.status) {
				case 400:
					error.message = '请求错误(400)';
					break;
				case 401:
					error.message = '未授权，请重新登录(401)';
					break;
				case 403:
					error.message = '拒绝访问(403)';
					break;
				case 404:
					error.message = '请求出错(404)';
					break;
				case 408:
					error.message = '请求超时(408)';
					break;
				case 500:
					error.message = '服务器错误(500)';
					break;
				case 501:
					error.message = '服务未实现(501)';
					break;
				case 502:
					error.message = '网络错误(502)';
					break;
				case 503:
					error.message = '服务不可用(503)';
					break;
				case 504:
					error.message = '网络超时(504)';
					break;
				case 505:
					error.message = 'HTTP版本不受支持(505)';
					break;
				default:
					error.message = `连接出错(${error.response.status})!`;
			}
		} else {
			error.message = error.msg || '连接服务器失败!'
		}
		Toast.fail({
			message: error.message,
			duration: 1500
		})
		//关闭loading
		hideLoading();
		return Promise.reject(error);
	}
)

export default service